apiready = function() {
    seajs.use(['../../V', "../../api", "../../jquery", "../../app", "../../service", "../../swiper", "../../dialog"], function(V, $api, $, app, service, Swiper, dialog) {
        var vm = {
            el: '.vue-content',
            data: {
                tagList: '', //标签的数组
                classfiyList: '', //分类的数组
                bigger: false, //控制前端轮播图的css
                small: false,

                isRecommend: false, //热门推荐 boolean值
                isGroup: false, //极速拼团 boolean值
                templateList: ['1'], //初始化商品型号模版数组
                detailData: [],

                category_id: '', //新建分类返回的id
                cat_name: '', //分类名称显示
                imgarr: '', //上传图片返回的地址字符串（接口用）
                num: '', //已上传图片数量
                swiperImageArr: [], //轮播图的图片数组
                mySwiper: '', //swiper对象
                titleContent: '',
                kill_start_time: '',
                kill_end_time: '',
                goodsSpec: [], //商品型号
                imgSpec: [], //商品型号对应的图片
                killPrice: [], //秒杀价格
                goodsPrice: [],
                marketPrice: [''],
                goodsNum: [],
                goodsCode: [],
                description: '',
                reason_tag: ['请选择'],

                edit: '',
                goodsList: [],
                textNum: 0,
                on_sale: 1,
                goods_id: ''
            },
            created: function() {
                var that = this;
                var shopId = api.pageParam.shopId; // 商店id
                var unionid = $api.getStorage("shop_unionid"); // 用户id

                //--获取分类列表
                this.getCat();

                //--编辑商品
                this.edit = api.pageParam.edit;
                if (this.edit == 1) {
                    var goodsId = api.pageParam.goods_id; // 商品id
                    this.goods_id = goodsId;
                    console.log("goodsId" + goodsId)
                    app.ajax(service['getShopDetail'], {
                            data: {
                                values: {
                                    goods_id: goodsId
                                }
                            }
                        },
                        function(res) {
                            // var shopCode = res.data.shop_code; // 商店id
                            if (res.code) {
                                api.toast({
                                    msg: res.message,
                                    duration: 2000,
                                    location: 'middle'
                                });

                            } else {
                                that.goodsList = res.data;
                                that.titleContent = that.goodsList.name;
                                that.textNum = that.titleContent.length;
                                that.on_sale = that.goodsList.on_sale;

                                //--有商品图片
                                if (that.goodsList.goods_images.length > 0) {
                                    for (var i = 0; i < that.goodsList.goods_images.length; i++) {
                                        that.swiperImageArr[i] = that.goodsList.goods_images[i].url;
                                    }
                                    console.log(JSON.stringify(that.swiperImageArr));
                                    //--前端为轮播图增加class
                                    that.bigger = true;
                                    that.small = true;
                                    that.num = that.goodsList.goods_images.length;

                                    // var image_arr = that.swiperImageArr;
                                    // var str1 = image_arr.join("|");
                                    // that.imgarr = str1;
                                    // console.log("往接口传的图片字符串到底是什么："+that.imgarr+" typeof: "+ typeof that.imgarr +"222\n");
                                    that.$nextTick(function() {
                                        that.mySwiper.destroy(false);
                                        that.startSwiper();
                                    })
                                }

                                //--商品信息
                                if (that.goodsList.goods_options.length > 0) {
                                    var sku = that.goodsList.goods_options;
                                    for (var i = 0; i < sku.length; i++) {
                                        if (i != 0) {
                                            that.templateList.push(1);
                                        }
                                        that.goodsSpec[i] = sku[i].name;

                                        that.goodsPrice[i] = sku[i].sale_price;
                                        that.marketPrice[i] = sku[i].market_price;
                                        that.goodsNum[i] = sku[i].stock;
                                        that.goodsCode[i] = sku[i].goods_sn;
                                        that.imgSpec[i] = sku[i].option_image;
                                    }
                                }

                                //--分类
                                if (that.goodsList.goods_categorys.length > 0) {
                                    var cat = that.goodsList.goods_categorys;
                                    that.category_id = cat[0].category_id;
                                    that.cat_name = cat[0].name;
                                }

                                //--商品详情
                                var detail_arr = that.goodsList.description.split('><').join('>|||<').split('|||')
                                that.detailData = detail_arr;
                            }
                        });

                } else {
                    $('.kill_price_class').css('display', 'none')
                }





                //--添加商品详情事件监听
                api.addEventListener({
                    name: 'shopAdd'
                }, function(ret, err) {
                    if (ret) {
                        that.description = ret.value.goodsDescription;
                        that.detailData = ret.value.detailData;
                    } else {
                        alert(JSON.stringify(err));
                    }

                });

                //--添加商品型号图片事件监听
                api.addEventListener({
                    name: 'shopImgAdd'
                }, function(ret, err) {
                    if (ret) {
                        Vue.set(that.imgSpec, ret.value.inds, ret.value.imgChosen); //商品型号对应的图片
                    } else {
                        alert(JSON.stringify(err));
                    }
                });

                //--添加图片事件监听
                api.addEventListener({
                    name: 'shopAddImgManage'
                }, function(ret, err) {
                    if (ret) {
                        that.swiperImageArr = ret.value.imgList; //轮播图图片

                        that.num = ret.value.num; //已上传图片数量
                        if (that.num > 0) {
                            that.bigger = true;
                            that.small = true;
                        } else {
                            that.bigger = false;
                            that.small = false;
                        }
                        that.$nextTick(function() {
                            that.mySwiper.destroy(false);
                            that.startSwiper();
                        })

                    } else {
                        alert(JSON.stringify(err));
                    }
                });

                //--键盘监听（解决ios键盘弹出后顶部样式混乱的问题）
                api.addEventListener({
                    name: 'keyboardshow'
                }, function(ret, err) {
                    $('.header').css({
                        'top': 0,
                        'position': 'static'
                    });
                });
                api.addEventListener({
                    name: 'keyboardhide'
                }, function(ret, err) {
                    $('.header').css({
                        'top': 0,
                        'position': 'fixed'
                    });
                });


            },
            mounted: function() {
                var that = this;
                this.startSwiper();

                //--限制商品标题输入（30个字符）
                $(".shop_add_text").keyup(function() {
                    that.textNum = that.titleContent.length;
                    // console.log(that.textNum)
                    if (that.textNum >= 30) {
                        that.textNum = 30;
                        that.titleContent = that.titleContent.substring(0, 30)
                        return false;
                    }
                });
                //--保证在输入中文时也会实时更新textNum
                var eventName = (navigator.userAgent.indexOf("MSIE") != -1) ? "propertychange" : "input";
                $(".shop_add_text").bind(eventName, function() {
                    that.textNum = that.titleContent.length;
                });

                //--解决ios输入法挡住输入框的问题
                $(document).on("focus", "#aui-input", function() {
                    setTimeout(function() {
                        console.log(document.body.offsetHeight);
                        window.scrollTo(0, document.body.offsetHeight - 280);
                    }, 50);
                });
            },

            methods: {
                //--点击返回按钮事件
                close: function() {
                    api.closeWin({
                        name: 'shopAddMember'
                    });
                },
                //--初始化轮播图
                startSwiper: function() {
                    var that = this;
                    var mySwiper = new Swiper('.swiper-container', {
                        pagination: {
                            el: '.swiper-pagination',
                            type: 'fraction'
                        },
                        observer: true,
                        observeParents: true,
                    })
                    this.mySwiper = mySwiper;
                },
                //--获取分类列表
                getCat: function() {
                    var shopId = api.pageParam.shopId; // 商店id
                    var unionid = $api.getStorage("shop_unionid"); // 用户id
                    var that = this;

                    app.ajax(service['getCategory'], {
                            data: {
                                values: {
                                    unionid: unionid,
                                    shop_code: shopId
                                }
                            }
                        },
                        function(res) {
                            // var shopCode = res.data.shop_code; // 商店id
                            if (res.code) {
                                api.toast({
                                    msg: res.message,
                                    duration: 2000,
                                    location: 'middle'
                                });
                            } else {
                                that.classfiyList = res.data;
                                console.log(res);
                            }
                        });

                },
                openImgSelect: function(inds) {
                    if (this.swiperImageArr.length < 1) {
                        api.toast({
                            msg: '请先添加商品图片',
                            duration: 2000,
                            location: 'middle'
                        });
                        return
                    }
                    app.openWin('imgSelect', {
                        imgArr: this.swiperImageArr,
                        inds: inds
                    }, {
                        reload: true
                    });
                },

                //--保存或者编辑商品信息，上传到接口
                saveOrEditGoods: function() {
                    // var isGroup = this.imgSpec;
                    // console.log(JSON.stringify(isGroup));
                    // return;

                    var shopId = api.pageParam.shopId; // 商店id
                    var unionid = $api.getStorage("shop_unionid"); // 用户id

                    var str1 = this.swiperImageArr.join("|");
                    this.imgarr = str1;
                    // console.log(this.imgarr)
                    // return

                    var images = this.imgarr; //商品图片
                    var goodsName = $api.trim(this.$refs.goodsName.value); //商品标题

                    var goodsPrice = this.goodsPrice; //商品价格
                    var marketPrice = this.marketPrice; //商品市场价格
                    var goodsSpec = this.goodsSpec; //商品型号
                    var goodsNum = this.goodsNum; //商品库存
                    var goodsCode = this.goodsCode; //商品编码
                    var imgSpec = this.imgSpec; //商品型号的图片
                    var description = $api.trim(this.description); //商品详情
                    var category_id = this.category_id; //分类ID
                    var on_sale = this.on_sale;
                    var goods_id = this.goods_id;
                    var skus = '';


                    if (goodsSpec.length < 1 || goodsNum.length < 1 || imgSpec.length < 1) {
                        api.toast({
                            msg: '请完整填写相应的商品信息...',
                            duration: 2000,
                            location: 'middle'
                        });
                        return;
                    }

                    // console.log(JSON.stringify(this.goodsPrice));
                    // console.log(JSON.stringify(this.marketPrice));
                    // console.log(JSON.stringify(this.goodsSpec));
                    // console.log(JSON.stringify(this.goodsNum));
                    // console.log(JSON.stringify(this.groupPrice));
                    // console.log(JSON.stringify(this.groupNum));
                    //
                    // return

                    for (var i = 0; i < this.templateList.length; i++) {

                        if (goodsSpec[i] == '' || goodsSpec[i] == null) {
                            api.toast({
                                msg: '请填写商品型号...',
                                duration: 2000,
                                location: 'middle'
                            });
                            return;
                        }
                        if (goodsNum[i] == '' || goodsNum[i] == null) {
                            api.toast({
                                msg: '请填写商品库存...',
                                duration: 2000,
                                location: 'middle'
                            });
                            return;
                        } else {
                            if (app.hasSpecialChar(goodsNum[i], '商品库存只能为整数...', 'greaterZeroInteger')) {
                                return
                            }
                            var num = parseInt(goodsNum[i]);
                            if (num < 0) {
                                api.toast({
                                    msg: '商品库存超过限制...',
                                    duration: 2000,
                                    location: 'middle'
                                });
                                return;
                            }
                        }
                        if (imgSpec[i] == '' || imgSpec[i] == null) {
                            api.toast({
                                msg: '请选择与商品型号对应的图片...',
                                duration: 2000,
                                location: 'middle'
                            });
                            return;
                        }


                        skus += goodsSpec[i] + ',"",' + 198 + ',"","","","",' + goodsNum[i] + ',"",' + imgSpec[i] + '|';

                    }


                    skus = skus.substring(0, skus.length - 1); //拼接skus字符串

                    if (goodsName == '' || goodsName == null) {
                        api.toast({
                            msg: '请填写商品标题...',
                            duration: 2000,
                            location: 'middle'
                        });
                        return;
                    } else if (goodsName.length > 100) {
                        api.toast({
                            msg: '商品标题超过上限...',
                            duration: 2000,
                            location: 'middle'
                        });
                        return;
                    }
                    if (images == '' || images == null) {
                        api.toast({
                            msg: '请添加商品图片...',
                            duration: 2000,
                            location: 'middle'
                        });
                        return;
                    }

                    if (this.edit != 1) {
                        app.ajax(service['goodsAdd'], {
                                data: {
                                    values: {
                                        is_member_product: 1, //会员商品记号
                                        shop_code: shopId,
                                        unionid: unionid,
                                        images: images,
                                        name: goodsName,
                                        category_id: category_id,
                                        skus: skus,
                                        description: description,
                                        on_sale: on_sale
                                    }
                                }
                            },
                            function(res) {
                                // var shopCode = res.data.shop_code; // 商店id
                                if (res.code) {
                                    api.toast({
                                        msg: res.message,
                                        duration: 2000,
                                        location: 'middle'
                                    });
                                } else {
                                    api.sendEvent({
                                        name: 'finishGoodsAdd'
                                    });
                                    api.sendEvent({
                                        name: 'backToGoodsManage'
                                    });
                                    api.closeWin()
                                    // app.openWin('shopEditMember', {
                                    //     shopId: api.pageParam.shopId
                                    // });
                                }
                            });
                    } else {
                        app.ajax(service['goodsEdit'], {
                                data: {
                                    values: {
                                        is_member_product: 1, //会员商品记号
                                        shop_code: shopId,
                                        unionid: unionid,
                                        goods_id: goods_id,
                                        images: images,
                                        name: goodsName,
                                        category_id: category_id,
                                        skus: skus,
                                        description: description,
                                        on_sale: on_sale
                                    }
                                }
                            },
                            function(res) {
                                // var shopCode = res.data.shop_code; // 商店id
                                if (res.code) {
                                    api.toast({
                                        msg: res.message,
                                        duration: 2000,
                                        location: 'middle'
                                    });
                                } else {

                                    alert("编辑会员商品成功!");
                                    //--发送事件（使商品管理页面刷新）
                                    api.sendEvent({
                                        name: 'backToGoodsManage',
                                    });
                                }
                            });
                    }
                },
                //--打开上传图片页面
                openImgManage: function() {
                    app.openWin('shopAddImgManage', {
                        imgArr: this.swiperImageArr
                    })
                },
                //--批量上传图片
                getPictureS: function() {
                    var that = this;
                    app.getPictureS(8, this.num, service['fileupload'], function(res) {
                        if (res.length > 0) {
                            api.toast({
                                msg: '上传成功',
                                duration: 2000,
                                location: 'middle'
                            });
                            // console.log("我传的图片字符串到底是什么："+res+" typeof: "+ res.constructor +"1111\n");
                            // var str1 = res.join("|");
                            // if(that.imgarr==''){
                            // 	that.imgarr = str1;
                            // }else{
                            // 	that.imgarr = that.imgarr + '|' + str1;
                            // }
                            // console.log("往接口传的图片字符串到底是什么："+that.imgarr+" typeof: "+ typeof that.imgarr +"222\n");

                            //前端为轮播图增加class
                            that.bigger = true;
                            that.small = true;
                            that.num = that.num + res.length;

                            that.swiperImageArr.push(res);
                            console.log("第一步：" + that.swiperImageArr + " typeof: " + that.swiperImageArr.constructor + "1111\n");
                            var str4 = that.swiperImageArr.join(",");
                            console.log("第一步：" + str4 + " typeof: " + str4.constructor + "1111\n");
                            that.swiperImageArr = str4.split(",");
                            console.log("第三步：" + that.swiperImageArr + " typeof: " + that.swiperImageArr.constructor + "1111\n");
                            // console.log(that.swiperImageArr[0]+" &Length:"+that.swiperImageArr.length+" &typeof: "+typeof that.swiperImageArr +"\n")
                            // console.log(JSON.stringify(that.swiperImageArr) +" : "+that.swiperImageArr.constructor);
                            that.$nextTick(function() {
                                that.mySwiper.destroy(false);
                                $(".swiper-pagination").css("display", "block")
                                that.startSwiper() // swiper重新初始化
                            })
                        }
                    })
                },
                //--添加商品型号
                addGoods: function(e) {
                    if (e.target.nodeName == 'DIV') {
                        this.templateList.push('1');
                        this.reason_tag.push('请选择');
                    }

                },
                //--删除商品型号
                addModelDel: function(index) {
                    console.log("号码是多少：" + index)
                    console.log(JSON.stringify(this.templateList));
                    this.templateList.splice(index, 1);
                    this.goodsSpec.splice(index, 1);
                    this.goodsPrice.splice(index, 1);
                    this.marketPrice.splice(index, 1);
                    this.goodsNum.splice(index, 1);
                    this.goodsCode.splice(index, 1);
                    this.reason_tag.splice(index, 1);
                    this.imgSpec.splice(index, 1);
                },
                //--打开商品详情页
                goodsDetail: function() {
                    app.openWin('goodsDetail', {
                        shopGoodsContent: this.detailData
                    })
                },
                //---------------------------------------------
                //--点击选择分类
                goodsClassfiy: function() {
                    $('.batch_classfiy').css("display", "block");
                    $('body, html').css("z-index", "-1");
                },
                close_batch_classfiy: function() {
                    $('.batch_classfiy').css("display", "none");
                    this.category_id = '';
                },
                //--点击分类选择事件
                getCategory: function(cat_id) {
                    console.log(this.category_id);

                    if (this.category_id == cat_id) {
                        this.category_id = '';
                        $('.batch_classfiy').find('.aui-radio').prop('checked', false);
                    } else {
                        this.category_id = cat_id;
                    }
                },
                //--取消选择分类
                classfiyCancel: function(et) {
                    $('.batch_classfiy').css("display", "none");
                    this.category_id = '';
                    $('.batch_classfiy').find('.aui-radio').prop('checked', false);
                },
                //--确定选择分类
                classfiySure: function() {
                    $('.batch_classfiy').css("display", "none");
                    this.cat_name = $("input[name='classifyName']:checked").siblings('span').html();
                },
                //--新建分类
                newClassfiy: function(et) {
                    var that = this;
                    var shopId = api.pageParam.shopId; // 商店id
                    var unionid = $api.getStorage("shop_unionid"); // 用户id

                    dialog.prompt({
                        title: "新建分类",
                        text: "输入分类名称",
                        buttons: ['取消', '确定']
                    }, function(ret) {
                        // alert(JSON.stringify(ret));
                        if (ret.buttonIndex == 2) { //  确认
                            var name = $api.trim(ret.text);

                            if (name == '' || name == null) {
                                api.toast({
                                    msg: "请输入正确的分类名称...",
                                    duration: 2000,
                                    location: 'middle'
                                });
                                name.value = '';
                                return false;
                            } else if (name.length > 10) {
                                api.toast({
                                    msg: "名称字数超过上限...",
                                    duration: 2000,
                                    location: 'middle'
                                });
                                return false;
                            }
                            //--判断是否存在特殊字符
                            if (app.hasSpecialChar(name, '请正确输入分类名称...', '')) {
                                return
                            }

                            app.ajax(service['addCategory'], {
                                    data: {
                                        values: {
                                            shop_code: shopId,
                                            unionid: unionid,
                                            name: name
                                        }
                                    }
                                },
                                function(res) {
                                    //返回category_id
                                    if (res.code) {
                                        api.toast({
                                            msg: res.message,
                                            duration: 2000,
                                            location: 'middle'
                                        });
                                    } else {
                                        that.category_id = res.data;
                                        console.log(this.category_id);
                                        alert("新建分类成功！");

                                        that.getCat();
                                    }
                                });
                        }
                    })
                },
                //---------------------------------------
                //--下架商品
                offButton: function(goods_id) {
                    var shopId = api.pageParam.shopId; // 商店id
                    var unionid = $api.getStorage("shop_unionid"); // 用户id
                    var that = this;

                    dialog.alert({
                        title: "商品下架提示",
                        msg: '请确认是否下架该商品',
                        buttons: ['取消', '确定']
                    }, function(ret) {
                        if (ret.buttonIndex == 2) { //确认
                            app.ajax(service['productOnSale'], {
                                    data: {
                                        values: {
                                            shop_code: shopId,
                                            unionid: unionid,
                                            goods_id: goods_id,
                                            on_sale: 0
                                        }
                                    }
                                },
                                function(res) {
                                    //返回category_id
                                    if (res.code) {
                                        api.toast({
                                            msg: res.message,
                                            duration: 2000,
                                            location: 'middle'
                                        });
                                    } else {
                                        that.on_sale = 0;
                                        api.toast({
                                            msg: '商品已下架',
                                            duration: 2000,
                                            location: 'middle'
                                        });

                                        //--发送事件（使商品管理页面刷新）
                                        api.sendEvent({
                                            name: 'backToGoodsManage',
                                        });
                                    }
                                });
                        }
                    })
                },
                //--上架商品
                onButton: function(goods_id) {
                    var shopId = api.pageParam.shopId; // 商店id
                    var unionid = $api.getStorage("shop_unionid"); // 用户id
                    var that = this;

                    app.ajax(service['productOnSale'], {
                            data: {
                                values: {
                                    shop_code: shopId,
                                    unionid: unionid,
                                    goods_id: goods_id,
                                    on_sale: 1
                                }
                            }
                        },
                        function(res) {
                            //返回category_id
                            if (res.code) {
                                api.toast({
                                    msg: res.message,
                                    duration: 2000,
                                    location: 'middle'
                                });
                            } else {
                                that.on_sale = 1;
                                api.toast({
                                    msg: '商品已上架',
                                    duration: 2000,
                                    location: 'middle'
                                });
                                //--发送事件（使商品管理页面刷新）
                                api.sendEvent({
                                    name: 'backToGoodsManage',
                                });
                            }
                        });

                },
                //--删除商品
                delButton: function(goods_id) {
                    var shopId = api.pageParam.shopId; // 商店id
                    var unionid = $api.getStorage("shop_unionid"); // 用户id
                    var that = this;

                    dialog.alert({
                        title: "商品回收提示",
                        msg: '请确认是否删除该商品',
                        buttons: ['取消', '确定']
                    }, function(ret) {
                        if (ret.buttonIndex == 2) { //确认
                            app.ajax(service['productDel'], {
                                    data: {
                                        values: {
                                            shop_code: shopId,
                                            unionid: unionid,
                                            goods_id: goods_id
                                        }
                                    }
                                },
                                function(res) {
                                    //返回category_id
                                    if (res.code) {
                                        api.toast({
                                            msg: res.message,
                                            duration: 2000,
                                            location: 'middle'
                                        });
                                    } else {
                                        api.toast({
                                            msg: '商品已删除',
                                            duration: 2000,
                                            location: 'middle'
                                        });

                                        //--发送事件（使商品管理页面刷新）
                                        api.sendEvent({
                                            name: 'backToGoodsManage',
                                        });

                                        api.closeWin();

                                    }
                                });
                        }
                    });
                },
                //--打开发布商品规则页面
                openAddRules: function() {
                    app.openWin('shopAddRules');
                },
            }
        };
        // var shopVue = new Vue(vm);
        var even = function() {


        };
        var newVue = new Vue(vm);
        even();

    })
}
